import { View, Input } from "@tarojs/components";
import { cva } from "class-variance-authority";
import { twMerge } from "tailwind-merge";

import ByIcon from "./ByIcon";
import useCounter from "@/hooks/useCounter";

type ByCounterProps = {
  value?: number;
  initialValue?: number;
  precision?: number;
  border?: boolean;
  size?: "small";
  min?: number;
  max?: number;
  className?: string;
};

type ByCounterEvents = {
  onBlur?: (event: any) => void;
  onChange?: (e: number) => void;
};

const wrapCls = cva("inline-flex items-center rounded-md", {
  variants: {
    border: {
      true: "border-1 border-line-light",
    },
    size: {
      // small: "py-1",
      // default: "py-2",
    },
  },
  defaultVariants: {
    border: true,
    // size: "default",
  },
});

export default ({
  className,
  border = true,
  
  max,
  min,
  value,
  precision,

  onBlur,
  onChange,
}: ByCounterProps & ByCounterEvents) => {
  const [count, { inc, dec, set }] = useCounter(value, {
    max,
    min,
    precision,
    onChange,
  });

  return (
    <View
      className={twMerge(wrapCls({ border }), className)}
      onClick={(event) => event.stopPropagation()}
    >
      <View className="flex-center p-2">
        <ByIcon name="Reduce" size={border ? 28 : 20} onClick={() => dec()} />
      </View>

      <Input
        type="digit"
        value={count + ""}
        className={`text-center rounded-sm ${
          border ? "mx-2 flex-auto" : "mx-1 w-[70px] bg-page"
        } `}
        onInput={(e) => set(e.detail.value)}
        onBlur={onBlur}
      />

      <View className="flex-center p-2">
        <ByIcon name="Plus" size={border ? 28 : 20} onClick={() => inc()} />
      </View>
    </View>
  );
};
